package com.feihong.txgw.tx_precenter;

import android.content.Intent;
import android.util.Log;

import com.feihong.txgw.R;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.inter.contract.order.IOrderContract;
import com.feihong.txgw.json.user.AllOrderInfo;
import com.feihong.txgw.model.base_bean.BaseResponse;
import com.feihong.txgw.tx_model.OrderMainModel;
import com.feihong.txgw.ui.activity.kaika.KaiKaActivity;
import com.feihong.txgw.ui.activity.order.KaiKaOrderDetailActivity;
import com.feihong.txgw.ui.activity.order.PayActivity;
import com.feihong.txgw.ui.activity.order.ProductsOrderDetailsActivity;
import com.feihong.txgw.ui.activity.order.ReViewOrderActivity;

import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @Author wangziheng
 * @ProjectName txgw_app
 * @ClassName OrderMainPrecenter
 * @package com.feihong.txgw.tx_precenter
 * @data 2018/5/7 10:39
 * @Describe
 * @Change
 */
public class OrderMainPrecenter extends IOrderContract.AbOrderMainPrecenter {

    /**
     * 是否满屏
     */
    private boolean isFullPage = false;
    private int mCurrentPageNum = 1;
    /**
     * 订单操作标识  1 取消 2 删除  3  确认收货
     */
    private int mOperateTag = 0;
    /**
     * 订单类型
     */
    private int mOrderType;

    private AllOrderInfo.DataBean.OrderPageBean mOrderInfo;

    private String resultErrorStr;
    public static OrderMainPrecenter create() {
        return new OrderMainPrecenter();
    }

    @Override
    public IOrderContract.IOrderMainModel getModel() {
        return OrderMainModel.create();
    }

    @Override
    public void onStart() {

    }

    /**
     * 加载订单列表
     *
     * @param ordreStatus
     */
    @Override
    public void loadOrderInfo(int ordreStatus) {
        int requestOrderStatus = ordreStatus;
        resultErrorStr = null;
        switch (ordreStatus) {
            case 0:
                resultErrorStr = "暂无订单";
                break;
            case 1:
                resultErrorStr = "暂无待支付订单";
                break;
            case 3:
                resultErrorStr = "暂无待收货订单";
                break;
            case 4:
                resultErrorStr = "暂无待评价订单";
                requestOrderStatus = 9;
                break;
            case 8:
                resultErrorStr = "暂无退款中订单";
                requestOrderStatus = 7;
                break;
            default:
                break;
        }
        final String finalResultErrorStr = resultErrorStr;
        int pageNum = mCurrentPageNum;
        mIModel.getOrderInfo(String.valueOf(pageNum), requestOrderStatus).subscribe(new Observer<AllOrderInfo>() {
            @Override
            public void onSubscribe(Disposable d) {
                mRxManager.register(d);
            }

            @Override
            public void onNext(AllOrderInfo orderInfo) {
                if (orderInfo.getCode() == 200 && orderInfo.getData() != null) {
                    // 判断数据是否填满当前页面 只对第一次加载做判断
                    if (isFullPage && mCurrentPageNum <= 1) {
                        isFullPage = orderInfo.getData().getOrder_page().size() > 3;
                    }
                    mCurrentPageNum++;
                    mIView.loadOrderResult(isFullPage, orderInfo.getData().getOrder_page());
                } else if (orderInfo.getCode() == 2021 || orderInfo.getData() == null) {
                    mIView.loadEnd(finalResultErrorStr);
                } else {
                    mIView.loadOtherError(orderInfo.getMsg());
                }
            }

            @Override
            public void onError(Throwable e) {
                mIView.loadDataError();
            }

            @Override
            public void onComplete() {

                mIView.loadDataComplated();
            }
        });

    }

    @Override
    public void loadOrderInfoFirst(int orderStatus) {
        isFullPage = false;
        mCurrentPageNum = 1;
        loadOrderInfo(orderStatus);
    }

    /**
     * item点击监听
     *
     * @param orderInfo
     */
    @Override
    public void onItemClick(AllOrderInfo.DataBean.OrderPageBean orderInfo,int itemPosition) {

        int table_id = Integer.parseInt(orderInfo.getTable_id());
        String order_id = orderInfo.getOrder_id();
        if (table_id == PayActivity.PAY_TYPE_PRODUCT) {
            Intent intent = new Intent(mIView.getCurrentAcitivty(), ProductsOrderDetailsActivity.class);
            intent.putExtra("table_id", table_id);
            intent.putExtra("order_id", order_id);
            mIView.getCurrentAcitivty().startActivity(intent);
        } else if (table_id == PayActivity.PAY_TYPE_KAIKA) {
            Intent intent = new Intent();
            intent.setClass(mIView.getCurrentAcitivty(), KaiKaOrderDetailActivity.class);
            intent.putExtra("orderid", order_id);
            mIView.getCurrentAcitivty().startActivity(intent);
        }
    }

    /**
     * 左侧按钮(可以理解为取消按钮)监听
     * @param orderInfo
     */
    @Override
    public void onCancelBtnClick(AllOrderInfo.DataBean.OrderPageBean orderInfo) {
        mOrderInfo = orderInfo;
        mOrderType = Integer.parseInt(orderInfo.getTable_id());
        mOperateTag = 1;
        int status = Integer.parseInt(orderInfo.getStatus());
        final String orderID = orderInfo.getOrder_id();
        switch (mOrderType) {
            case PayActivity.PAY_TYPE_PRODUCT:
                // 终端订单 并且状态为已失败  可申请退款
                if (status == 6) {
                    // 申请退款操作
                } else if (status == 2) {
                    // 终端订单  并且已支付状态  可申请退款（如果处于未发货）

                    // 申请退款操作
                } else {
                    mIView.getCurrentAcitivty().showConfirmDialog("取消订单", "您确定要取消此订单信息吗？", "是", "否", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            mIView.getCurrentAcitivty().showProgressDialog("订单取消中");
                            mIModel.orderOpration(HttpTools.CANNEL_ORDER_URL_KEY, orderID, String.valueOf(mOrderType)).subscribe(orderOperateObserver);
                        }
                    });
                }
                break;
            case PayActivity.PAY_TYPE_KAIKA:
                // 开卡订单  并且状态为已失败  可申请退款
                if (status == 6) {
                    // 申请退款操作
                } else {
                    mIView.getCurrentAcitivty().showConfirmDialog("取消订单", "您确定要取消此订单信息吗？", "是", "否", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            mIView.getCurrentAcitivty().showProgressDialog("订单取消中");
                            mIModel.orderOpration(HttpTools.CANNEL_ORDER_URL_KEY, orderID, String.valueOf(mOrderType)).subscribe(orderOperateObserver);
                        }
                    });
                }
                break;
            case PayActivity.PAY_TYPE_PHONE_RECHARGE:
            case PayActivity.PAY_TYPE_PHONE_GPRS:
                if (status == 2) {
                    // 申请退款操作
                } else {
                    mIView.getCurrentAcitivty().showConfirmDialog("取消订单", "您确定要取消此订单信息吗？", "是", "否", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            mIView.getCurrentAcitivty().showProgressDialog("订单取消中");
                            mIModel.orderOpration(HttpTools.CANNEL_ORDER_URL_KEY, orderID, String.valueOf(mOrderType)).subscribe(orderOperateObserver);
                        }
                    });
                }
                break;
            default:
                break;
        }

    }

    /**
     * 右侧按钮监听(可以理解为确认按钮)
     * @param orderInfo
     */
    @Override
    public void onConfirmBtnClick(AllOrderInfo.DataBean.OrderPageBean orderInfo) {
        mOrderType = Integer.parseInt(orderInfo.getTable_id());
        mOrderInfo = orderInfo;
        switch (mOrderType) {
            case PayActivity.PAY_TYPE_KAIKA:
                //开卡的
                kaikaClick(orderInfo);
                break;
            case PayActivity.PAY_TYPE_PHONE_GPRS:
                //流量
            case PayActivity.PAY_TYPE_PHONE_RECHARGE:
                //充值
                chongzhiClick(orderInfo);
                break;
            case PayActivity.PAY_TYPE_PRODUCT:
                //终端
                zhongduanClick(orderInfo);
                break;
            default:
                break;
        }
    }

    private void kaikaClick(AllOrderInfo.DataBean.OrderPageBean orderPageBean) {
        final int type = Integer.parseInt(orderPageBean.getTable_id());
        int status = Integer.parseInt(orderPageBean.getStatus());
        String orderSN = orderPageBean.getOrder_sn();
        final String orderID = orderPageBean.getOrder_id();
        String price = orderPageBean.getPrice();
        String goodsID = orderPageBean.getSku_id();
        // 开卡0 待支付  1 已受理 (已支付)  2 正处理  3 已完成  4 已取消   (后台状态指示错误 ：取消中 (取消订单处理中))  5 退款中  6 已失败
        Intent intent = new Intent();
        // 如果是预约订单 并且
        if ("2".equals(orderPageBean.getOrder_type())) {

            switch (status) {
                case 0:
//                        if (fromBooking == 1) {
                    intent = new Intent(mIView.getCurrentAcitivty(), PayActivity.class);
                    intent.putExtra(PayActivity.INTENT_ORDER_ID, orderSN);
                    intent.putExtra(PayActivity.INTENT_PRICE, price);
                    intent.putExtra(PayActivity.INTENT_PAY_TYPE, type);
                    intent.putExtra(PayActivity.INTENT_FROM, 2);
                    mIView.getCurrentAcitivty().startActivity(intent);
//                        } else {
//                            //还未进行活体检测 则
//                            if ("0".equals(mList.get(pos).getHtjc_id())) {
//                                intent = new Intent(mContext, KaiKaStep4Activity.class);
//                                intent.putExtra(KaiKaActivity.INTENT_ORDERSN, mList.get(pos).getOrder_sn());
//                                mContext.startActivity(intent);
//                            } else {
//                                intent = new Intent(mContext, PayActivity.class);
//                                intent.putExtra(PayActivity.INTENT_ORDER_ID, orderSN);
//                                intent.putExtra(PayActivity.INTENT_PRICE, price);
//                                intent.putExtra(PayActivity.INTENT_PAY_TYPE, type);
//                                intent.putExtra(PayActivity.INTENT_FROM, 2);
//                                mContext.startActivity(intent);
//                            }
//                        }
                    break;
                case 1:
//                        if (fromBooking == 1) {
                    intent = new Intent(mIView.getCurrentAcitivty(), KaiKaActivity.class);
                    intent.putExtra(KaiKaActivity.INTENT_ORDERSN, orderPageBean.getOrder_sn());
                    intent.putExtra(KaiKaActivity.INTENT_FROM_BOOKING, 1);
                    mIView.getCurrentAcitivty().startActivity(intent);
//                        } else {
//                            if ("0".equals(mList.get(pos).getHtjc_id())) {
//                                intent = new Intent(mContext, KaiKaStep4Activity.class);
//                                intent.putExtra(KaiKaActivity.INTENT_ORDERSN, mList.get(pos).getOrder_sn());
//                                mContext.startActivity(intent);
//                            }
//                        }
                    break;
                case 4:
                    mOperateTag = 2;
                    //删除订单
                    mIView.getCurrentAcitivty().showConfirmDialog("删除订单", "您确定要删除此订单信息吗？", "删除", "取消", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            mIView.getCurrentAcitivty().showProgressDialog("订单删除中");
                            mIModel.orderOpration(HttpTools.DEL_ORDER_URL_KEY, orderID, String.valueOf(type)).subscribe(orderOperateObserver);

                        }
                    });
                    break;
                default:
                    break;
            }
        } else {
            switch (status) {
                case 0:
                    //付款
                    intent = new Intent(mIView.getCurrentAcitivty(), PayActivity.class);
                    intent.putExtra(PayActivity.INTENT_ORDER_ID, orderSN);
                    intent.putExtra(PayActivity.INTENT_PRICE, price);
                    intent.putExtra(PayActivity.INTENT_PAY_TYPE, type);
                    intent.putExtra(PayActivity.INTENT_FROM, 2);
                    mIView.getCurrentAcitivty().startActivity(intent);
                    break;
//                case 3://评价
//                    intent = new Intent(mContext, ReViewOrderActivity.class);
//                    intent.putExtra(PayActivity.INTENT_ORDER_ID, orderSN);
//                    intent.putExtra(PayActivity.INTENT_PRICE, Float.parseFloat(price));
//                    intent.putExtra(PayActivity.INTENT_PAY_TYPE, type);
//                    intent.putExtra(PayActivity.INTENT_GOODS_ID, goodsID);
//
//                    intent.putExtra("table_id", type);
//                    intent.putExtra("order_id", orderID);
////                    intent.putExtra("goodImg",mList.get(pos).get);
//                    mContext.startActivity(intent);
//                    break;
                case 4:
                    //删除订单
                    mOperateTag = 2;
                    mIView.getCurrentAcitivty().showConfirmDialog("删除订单", "您确定要删除此订单信息吗？", "删除", "取消", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            mIView.getCurrentAcitivty().showProgressDialog("订单删除中");
                            mIModel.orderOpration(HttpTools.DEL_ORDER_URL_KEY, orderID, String.valueOf(type)).subscribe(orderOperateObserver);

                        }
                    });
                    break;
                case 6:
                    break;
                default:
                    break;
            }
        }
    }

    private void chongzhiClick(AllOrderInfo.DataBean.OrderPageBean orderPageBean) {
        final int type = Integer.parseInt(orderPageBean.getTable_id());
        int status = Integer.parseInt(orderPageBean.getStatus());
        String orderSN = orderPageBean.getOrder_sn();
        final String orderID = orderPageBean.getOrder_id();
        String price = orderPageBean.getPrice();
        String goodsID = orderPageBean.getSku_id();
        // 话费和流量  0 待支付 (订单提交成功)  1 已受理 (已支付)  2 已失败  3 处理中  4 已完成  5 已取消  6 退款中
        Intent intent = new Intent();
        switch (status) {
            case 0:
                //付款
                intent = new Intent(mIView.getCurrentAcitivty(), PayActivity.class);
                intent.putExtra(PayActivity.INTENT_ORDER_ID, orderSN);
                intent.putExtra(PayActivity.INTENT_PRICE, price);
                intent.putExtra(PayActivity.INTENT_PAY_TYPE, type);
                intent.putExtra(PayActivity.INTENT_FROM, 2);
                mIView.getCurrentAcitivty().startActivity(intent);
                break;

//                case 4://评价
//                    intent = new Intent(mContext, ReViewOrderActivity.class);
//                    intent.putExtra(PayActivity.INTENT_ORDER_ID, orderSN);
//                    intent.putExtra(PayActivity.INTENT_PRICE, Float.parseFloat(price));
//                    intent.putExtra(PayActivity.INTENT_PAY_TYPE, type);
//                    intent.putExtra(PayActivity.INTENT_GOODS_ID, goodsID);
//
//
//                    intent.putExtra("table_id", type);
//                    intent.putExtra("order_id", orderID);
//                    mContext.startActivity(intent);
//                    break;
            case 2:
            case 4:
            case 5:
                //删除订单
                mOperateTag = 2;
                mIView.getCurrentAcitivty().showConfirmDialog("删除订单", "您确定要删除此订单信息吗？", "删除", "取消", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        mIView.getCurrentAcitivty().showProgressDialog("订单删除中");
                        mIModel.orderOpration(HttpTools.DEL_ORDER_URL_KEY, orderID, String.valueOf(type)).subscribe(orderOperateObserver);
                    }
                });
                break;
            default:
                break;
        }


    }

    private void zhongduanClick(AllOrderInfo.DataBean.OrderPageBean orderPageBean) {
        final int type = Integer.parseInt(orderPageBean.getTable_id());
        int status = Integer.parseInt(orderPageBean.getStatus());
        String orderSN = orderPageBean.getOrder_sn();
        final String orderID = orderPageBean.getOrder_id();
        String price = orderPageBean.getPrice();
        String goodsID = orderPageBean.getSku_id();
        //终端  1 待支付  2 已付款  3 已发货  4 已完成  5 已取消（除取消状态之外的其他状态的订单在应用端暂时无删除操作）  6 已失败  7 退款中
        Intent intent = new Intent();
        switch (status) {
            case 1:
                //付款
                intent = new Intent(mIView.getCurrentAcitivty(), PayActivity.class);
                intent.putExtra(PayActivity.INTENT_ORDER_ID, orderSN);
                intent.putExtra(PayActivity.INTENT_PRICE, price);
                intent.putExtra(PayActivity.INTENT_PAY_TYPE, type);
                intent.putExtra(PayActivity.INTENT_FROM, 2);
                mIView.getCurrentAcitivty().startActivity(intent);
                break;
            case 3:
                //待收货
                daishouhuoclick(orderPageBean);
                break;

            case 4:
                //评价
                intent = new Intent(mIView.getCurrentAcitivty(), ReViewOrderActivity.class);
                intent.putExtra(PayActivity.INTENT_ORDER_ID, orderSN);
                intent.putExtra(PayActivity.INTENT_PRICE, price);
                intent.putExtra(PayActivity.INTENT_PAY_TYPE, type);
                intent.putExtra(PayActivity.INTENT_GOODS_ID, goodsID);
                intent.putExtra("order_id", orderID);
                mIView.getCurrentAcitivty().startActivity(intent);
                break;
            case 5:
                mOperateTag = 2;
                //删除订单
                mIView.getCurrentAcitivty().showConfirmDialog("删除订单", "您确定要删除此订单信息吗？", "删除", "取消", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        mIView.getCurrentAcitivty().showProgressDialog("订单删除中");
                        mIModel.orderOpration(HttpTools.DEL_ORDER_URL_KEY, orderID, String.valueOf(type)).subscribe(orderOperateObserver);
                    }
                });
                break;
            case 6:
                //删除订单

                break;
            default:
                break;
        }
    }

    private void daishouhuoclick(AllOrderInfo.DataBean.OrderPageBean orderPageBean) {
        final int type = Integer.parseInt(orderPageBean.getTable_id());
        int status = Integer.parseInt(orderPageBean.getStatus());
        final String orderID = orderPageBean.getOrder_id();
        mIView.getCurrentAcitivty().showConfirmDialog("确认收货", "您确定要确认收货此订单吗？", "是", "否", new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
                mOperateTag = 3;
                mIView.getCurrentAcitivty().showProgressDialog("订单确认中");
                mIModel.orderOpration(HttpTools.CONFIRM_ORDER_URL_KEY, orderID, String.valueOf(type)).subscribe(orderOperateObserver);
            }
        });
    }

    Observer<BaseResponse> orderOperateObserver = new Observer<BaseResponse>() {
        @Override
        public void onSubscribe(Disposable d) {
            mRxManager.register(d);
        }

        @Override
        public void onNext(BaseResponse baseResponse) {
            boolean isNofityRemoveItem = false;
            mIView.getCurrentAcitivty().dismissProgressDialog();
            if (baseResponse.code == 200) {
                switch (mOperateTag) {
                    case 1:
                        isNofityRemoveItem = false;
                        switch (mOrderType) {
                            case PayActivity.PAY_TYPE_PHONE_RECHARGE:
                            case PayActivity.PAY_TYPE_PHONE_GPRS:
                            case PayActivity.PAY_TYPE_PRODUCT:
                                // 设置充值、终端订单为取消状态
                                mOrderInfo.setStatus("5");
                                break;
                            case PayActivity.PAY_TYPE_KAIKA:
                                // 设置开卡订单为取消状态
                                mOrderInfo.setStatus("4");
                                break;
                            default:
                                break;
                        }
                        break;
                    case 2:
                        isNofityRemoveItem = true;
                        break;
                    case 3:
                        // 设置终端订单状态为收货状态
                        isNofityRemoveItem = false;
                        mOrderInfo.setStatus("4");
                        break;
                    case 4:
                    case 5:
                        break;
                    default:
                        break;
                }
                // 刷新当前item
                mIView.notifyItemChange(mOrderInfo, isNofityRemoveItem,resultErrorStr);
                mIView.getCurrentAcitivty().showDialog("", baseResponse.msg);
            } else {
                mIView.getCurrentAcitivty().showDialog("", baseResponse.msg);
            }
        }

        @Override
        public void onError(Throwable e) {
            mIView.getCurrentAcitivty().dismissProgressDialog();
            mIView.getCurrentAcitivty().showDialog(null, mIView.getCurrentAcitivty().getResources().getString(R.string.connect_service_error));
        }

        @Override
        public void onComplete() {

        }
    };

    /**
     *
     *  int table_id = Integer.parseInt(orderInfo.getTable_id());
     String order_id = orderInfo.getOrder_id();
     Bundle bundle = new Bundle();
     bundle.putString("table_id",String.valueOf(table_id));
     if (table_id == PayActivity.PAY_TYPE_PRODUCT) {
     bundle.putString("order_id",order_id);
     mIView.getCurrentAcitivty().startActivityForResultInBaseActivity(ProductsOrderDetailsActivity.class,bundle,-1);
     } else if (table_id == PayActivity.PAY_TYPE_KAIKA) {
     mIView.getCurrentAcitivty().startActivityForResultInBaseActivity(KaiKaOrderDetailActivity.class,bundle,-1);
     }
     */
}
